package org.jeecg.modules.finance.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.LimitSubmit;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.business.service.ICaishuiBusinessService;
import org.jeecg.modules.finance.service.ICaishuiBillService;
import org.jeecg.modules.finance.service.ICaishuiRechargeService;
import org.jeecg.modules.finance.service.ICaishuiRefundRecordService;
import org.jeecg.modules.manage.entity.CaishuiBill;
import org.jeecg.modules.manage.entity.CaishuiBusiness;
import org.jeecg.modules.manage.entity.CaishuiRefundRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 开票记录[B端]
 * @Author: yfkj
 * @Date: 2023-02-23
 * @Version: V1.0
 */
@Api(tags = "开票记录[B端]")
@RestController
@RequestMapping("/finance/caishuiBill")
@Slf4j
public class CaishuiBillController extends JeecgController<CaishuiBill, ICaishuiBillService> {

    @Autowired
    private ICaishuiBillService caishuiBillService;
    @Autowired
    private ICaishuiRechargeService iCaishuiRechargeService;
    @Autowired
    private ICaishuiBusinessService iCaishuiBusinessService;
    @Autowired
    private ICaishuiRefundRecordService iCaishuiRefundRecordService;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 分页列表查询
     *
     * @param caishuiBill
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "开票记录[B端]-分页列表查询", notes = "开票记录[B端]-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<CaishuiBill>> queryPageList(CaishuiBill caishuiBill,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        QueryWrapper<CaishuiBill> queryWrapper = QueryGenerator.initQueryWrapper(caishuiBill, req.getParameterMap());
        queryWrapper.lambda().eq(CaishuiBill::getBusinessId, TokenUtils.getLoginUser().getCurBusiness());
        queryWrapper.lambda().eq(CaishuiBill::getCompanyId, TokenUtils.getLoginUser().getCurCompany());
        Page<CaishuiBill> page = new Page<CaishuiBill>(pageNo, pageSize);
        IPage<CaishuiBill> pageList = caishuiBillService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 查询开票统计
     *
     * @return
     */
    @ApiOperation(value = "开票记录[B端]-查询开票统计", notes = "开票记录[B端]-查询开票统计")
    @GetMapping(value = "/queryBillStatistics")
    public Result<?> queryBillStatistics() {
        //当前登录用户
        LoginUser loginUser = TokenUtils.getLoginUser();
        //充值总额
        Map<String, String> params = new HashMap<>();
        params.put("businessId",loginUser.getCurBusiness());
        params.put("companyId",loginUser.getCurCompany());
        params.put("status","1");
        Map<String,Object> map = iCaishuiRechargeService.queryTotalAmount(params);
        double rechargeTotalAmount = oConvertUtils.getDouble(map.get("amount")+"",0.00);

        double billAmount = 0.00;//开票金额
        double refundAmount = 0.00;//退款金额
        double billCanAmount = 0.00;//可开发票金额
        if(rechargeTotalAmount > 0){
            //开票金额（开票中+开票成功）
            params.put("status","");
            params.put("inStatus","0,1,2,7");
            billAmount = caishuiBillService.queryBillTotal(params);
            //退款金额（退款中+退款成功）
            params.put("status","");
            params.put("inStatus","0,1,3,4");
            map = iCaishuiRefundRecordService.queryRefundTotal(params);
            refundAmount = oConvertUtils.getDouble(map.get("money")+"",0.00);
            //可开发票金额 = 充值总额 - 开票金额（开票中+开票成功） - 退款金额（退款中+退款成功）
            billCanAmount = BigDecimal.valueOf(rechargeTotalAmount).subtract(BigDecimal.valueOf(billAmount)).subtract(BigDecimal.valueOf(refundAmount)).setScale(BigDecimal.ROUND_HALF_UP).doubleValue();
        }

        JSONObject result = new JSONObject(4);
        result.put("billCanAmount",billCanAmount);
        result.put("rechargeTotalAmount",rechargeTotalAmount);
        result.put("billAmount",billAmount);
        result.put("refundAmount",refundAmount);
        return Result.OK(result);
    }

    /**
     * 添加
     *
     * @param caishuiBill
     * @return
     */
    @AutoLog(value = "开票记录[B端]-申请开票", terminal = 2)
    @ApiOperation(value = "开票记录[B端]-申请开票", notes = "开票记录[B端]-申请开票")
    @PostMapping(value = "/add")
    @LimitSubmit(key = "business:bill:add:%bId:%cId")
    public Result<String> add(@RequestBody CaishuiBill caishuiBill) {
        //当前登录用户
        LoginUser loginUser = TokenUtils.getLoginUser();
        if(caishuiBill.getAmount() <= 0){
            return Result.error("请输入正确的开票金额！");
        }else {
            Result<?> result = queryBillStatistics();
            if(!result.isSuccess()){
                return Result.error("开票金额错误！");
            }
            //可开票金额
            JSONObject jsonObject = (JSONObject) result.getResult();
            double billCanAmount = oConvertUtils.getDouble(jsonObject.get("billCanAmount")+"",0);
            if(caishuiBill.getAmount() > billCanAmount){
                return Result.error("最多可开票金额：" + billCanAmount);
            }
        }

        //判断是否存在开票中的数据
        CaishuiBill bill = caishuiBillService.getOne(new LambdaQueryWrapper<CaishuiBill>()
                .select(CaishuiBill::getStatus).eq(CaishuiBill::getBusinessId,loginUser.getCurBusiness())
                .eq(CaishuiBill::getCompanyId,loginUser.getCurCompany()).orderByDesc(CaishuiBill::getCreateTime)
                .last("LIMIT 1"));
        if (oConvertUtils.isNotEmpty(bill) && oConvertUtils.isNotEmpty(bill.getStatus())){
            if (bill.getStatus()==0) return Result.error("请先操作完成上一笔【开票】信息！");
            if (bill.getStatus()==1) return Result.error("请耐心等待上一笔【开票】信息审核完成！");
            if (bill.getStatus()==2) return Result.error("请耐心等待上一笔【开票】信息处理完成！");
        }

        //判断是否存在退款中的数据
        CaishuiRefundRecord refundRecord = iCaishuiRefundRecordService.getOne(new LambdaQueryWrapper<CaishuiRefundRecord>()
                .select(CaishuiRefundRecord::getStatus).eq(CaishuiRefundRecord::getBusinessId,loginUser.getCurBusiness())
                .eq(CaishuiRefundRecord::getCompanyId,loginUser.getCurCompany()).orderByDesc(CaishuiRefundRecord::getCreateTime)
                .last("LIMIT 1"));
        if (oConvertUtils.isNotEmpty(refundRecord) && oConvertUtils.isNotEmpty(refundRecord.getStatus())){
            if (refundRecord.getStatus()==0) return Result.error("请先操作完成上一笔【退款】订单！");
            if (refundRecord.getStatus()==1) return Result.error("请先处理完成上一笔【退款】订单！");
            if (refundRecord.getStatus()==3) return Result.error("请耐心等待上一笔【退款】订单银行处理完成！");
        }

        //商户信息
        CaishuiBusiness business = iCaishuiBusinessService.getById(TokenUtils.getLoginUser().getCurBusiness());
        if(oConvertUtils.isEmpty(business)){
            return Result.error("商户信息错误！");
        }

        caishuiBill.setBusinessId(business.getId());
        caishuiBill.setTenantId(business.getTenantId());
        caishuiBill.setCompanyId(TokenUtils.getLoginUser().getCurCompany());
        caishuiBill.setOrderNo(FillRuleUtil.OrderNumberRule("FP",""));
        caishuiBill.setStatus(0);
        caishuiBill.setSubmitTime(new Date());
        caishuiBillService.save(caishuiBill);
        return Result.OK("申请成功！");
    }

    /**
     * 编辑
     *
     * @param caishuiBill
     * @return
     */
    @AutoLog(value = "开票记录[B端]-编辑", dataType = 2, terminal = 2)
    @ApiOperation(value = "开票记录[B端]-编辑", notes = "开票记录[B端]-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    @LimitSubmit(key = "business:bill:edit:%bId:%cId", spelKey = "#caishuiBill.id")
    public Result<String> edit(@RequestBody CaishuiBill caishuiBill) {
        if(caishuiBill.getAmount() <= 0){
            return Result.error("请输入正确的开票金额！");
        }else {
            Result<?> result = queryBillStatistics();
            if(!result.isSuccess()){
                return Result.error("开票金额错误！");
            }
            //可开票金额
            JSONObject jsonObject = (JSONObject) result.getResult();
            double billCanAmount = oConvertUtils.getDouble(jsonObject.get("billCanAmount")+"",0);
            CaishuiBill oldCaishuiBill = caishuiBillService.getById(caishuiBill.getId());
            if(oConvertUtils.isEmpty(oldCaishuiBill)){
                return Result.error("开票信息错误！");
            }
            if(caishuiBill.getAmount() > (billCanAmount + oldCaishuiBill.getAmount())){//编辑的时候可开票金额还得加上原来的金额
                return Result.error("最多可开票金额：" + billCanAmount);
            }
        }
        caishuiBillService.updateById(caishuiBill);
        return Result.OK("编辑成功!");
    }

    /**
     * 提交开票
     * @param id
     * @param status
     * @return
     */
    @AutoLog(value = "开票记录[B端]-提交开票", terminal = 2)
    @ApiOperation(value="开票记录[B端]-提交开票", notes="开票记录[B端]-提交开票")
    @GetMapping(value = "/statusOne")
    @LimitSubmit(key = "business:bill:statusOne:%bId:%cId", spelKey = "#id")
    public Result<?> statusOne(@RequestParam(name="id",required=true) String id,
                               @RequestParam(name="captcha",required=true) String captcha,
                               @RequestParam(name="status",required=true) int status) {
        //从缓存中获取手机验证码
        Object code = redisUtil.get(CommonConstant.PHONE_REDIS_KEY_PRE + TokenUtils.getLoginUser().getUsername());
        if(oConvertUtils.isEmpty(code)){
            return Result.error("短信验证码已失效！");
        }else if (!captcha.equals(code)) {
            return Result.error("短信验证码错误！");
        }

        CaishuiBill caishuiBill = caishuiBillService.getById(id);
        if(oConvertUtils.isEmpty(caishuiBill)){
            return Result.error("开票信息错误！");
        }else if(caishuiBill.getStatus() != 0){
            return Result.error("提交失败！");
        }

        caishuiBill.setStatus(1);
        caishuiBill.setSubmitTime(new Date());
        caishuiBillService.updateById(caishuiBill);
        return Result.OK("提交成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "开票记录[B端]-通过id删除", terminal = 2)
    @ApiOperation(value = "开票记录[B端]-通过id删除", notes = "开票记录[B端]-通过id删除")
    @DeleteMapping(value = "/delete")
    @LimitSubmit(key = "business:bill:delete:%bId:%cId", spelKey = "#id")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        caishuiBillService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "开票记录[B端]-批量删除", terminal = 2)
    @ApiOperation(value = "开票记录[B端]-批量删除", notes = "开票记录[B端]-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.caishuiBillService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "开票记录[B端]-通过id查询", notes = "开票记录[B端]-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<CaishuiBill> queryById(@RequestParam(name = "id", required = true) String id) {
        CaishuiBill caishuiBill = caishuiBillService.getById(id);
        if (caishuiBill == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(caishuiBill);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param caishuiBill
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CaishuiBill caishuiBill) {
        caishuiBill.setBusinessId(TokenUtils.getLoginUser().getCurBusiness());
        caishuiBill.setCompanyId(TokenUtils.getLoginUser().getCurCompany());
        return super.exportXls(request, caishuiBill, CaishuiBill.class, "开票记录[B端]");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CaishuiBill.class);
    }

}
